package ru.ksu.ktk.diploma.sdi.mapping.resolver.sampling;

import java.util.*;

import ru.ksu.ktk.diploma.sdi.mapping.MappingElement;

/**
 * sample list of elements according to conditions: 1) size of list is minimal; 2) list's elements with larger
 * normalized weights sum which is more than threshold
 * 
 * @author coldflame 15.04.2009 20:39:41
 */
public class SumThresholdCommand extends AbstractSamplingCommand {
    private float threshold;

    public SumThresholdCommand(float threshold) {
        this.threshold = threshold;
    }

    public List<MappingElement> execute() {
        List<MappingElement> sampledElements = new ArrayList<MappingElement>();
        List<MappingElement> mappingElements = context.getMappingElements();
        int weightSum = 0;
        for (MappingElement mappingElement : mappingElements){
            weightSum += mappingElement.getWeight();
        }
        Collections.sort(mappingElements, new MappingElementDescComparator());
        float normSum = 0;
        for (MappingElement mappingElement : mappingElements){
            float normWeight = ((float) mappingElement.getWeight()) / weightSum;
            normSum += normWeight;
            sampledElements.add(mappingElement);
            if (normSum > threshold){
                break;
            }
        }
        return sampledElements;
    }

    private static class MappingElementDescComparator implements Comparator<MappingElement> {

        public int compare(MappingElement first, MappingElement second) {
            int weight = first.getWeight();
            int otherWeight = second.getWeight();
            if (weight > otherWeight) return -1;
            if (weight < otherWeight) return 1;
            return 0;
        }

    }

}
